import pygame
import sys
from config import Config
from game import GameLogic
from ui import GridView, ControlPanel, DataDisplay
from utils import FontManager

class GameOfLife:
    def __init__(self):
        # 初始化Pygame
        pygame.init()
        pygame.display.set_caption(Config.WINDOW_TITLE)
        
        # 初始化字体管理器
        self.font_manager = FontManager()
        
        # 创建窗口
        self.screen = pygame.display.set_mode(
            (Config.WINDOW_WIDTH, Config.WINDOW_HEIGHT)
        )
        self.clock = pygame.time.Clock()
        
        # 创建游戏逻辑
        self.game_logic = GameLogic(Config.GRID_COLS, Config.GRID_ROWS)
        
        # 计算布局
        panel_width = Config.PANEL_WIDTH
        grid_width = Config.WINDOW_WIDTH - panel_width
        
        # 创建UI组件
        self.grid_view = GridView(
            self.game_logic,
            pygame.Rect(0, 0, grid_width, Config.WINDOW_HEIGHT)
        )
        
        # 计算面板高度
        panel_height = Config.WINDOW_HEIGHT
        data_height = panel_height // 3
        control_height = panel_height - data_height
        
        # 创建数据显示（放在上方）
        self.data_display = DataDisplay(
            self.game_logic,
            pygame.Rect(grid_width, 0, panel_width, data_height)
        )
        
        # 创建控制面板（放在下方）
        self.control_panel = ControlPanel(
            self.game_logic,
            pygame.Rect(grid_width, data_height, panel_width, control_height)
        )
        
        # 设置更新速度
        self.update_interval = 1000 // Config.DEFAULT_SPEED  # 毫秒
        self.last_update = 0
        
        # 设置速度改变回调
        self.control_panel.on_speed_change = self.on_speed_change
    
    def handle_events(self):
        """处理所有事件"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False
            
            # 处理按键事件
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return False
                elif event.key == pygame.K_SPACE:
                    self.game_logic.pause()
            
            # 将事件传递给UI组件
            if self.grid_view.handle_event(event):
                continue
            if self.control_panel.handle_event(event):
                continue
        
        return True
    
    def update(self):
        """更新游戏状态"""
        current_time = pygame.time.get_ticks()
        
        # 更新游戏逻辑
        if (self.game_logic.running and not self.game_logic.paused and 
            current_time - self.last_update >= self.update_interval):
            self.game_logic.update()
            self.last_update = current_time
        
        # 更新UI组件
        self.control_panel.update()
        self.data_display.update()
    
    def draw(self):
        """绘制游戏画面"""
        # 清空屏幕
        self.screen.fill(Config.BACKGROUND_COLOR)
        
        # 绘制UI组件
        self.grid_view.draw(self.screen)
        self.control_panel.draw(self.screen)
        self.data_display.draw(self.screen)
        
        # 更新显示
        pygame.display.flip()
    
    def on_speed_change(self, value):
        """处理速度改变"""
        self.update_interval = 1000 // value
    
    def run(self):
        """运行游戏主循环"""
        running = True
        while running:
            running = self.handle_events()
            self.update()
            self.draw()
            self.clock.tick(60)  # 限制帧率
        
        pygame.quit()
        sys.exit()

if __name__ == "__main__":
    game = GameOfLife()
    game.run()